from django import http
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.utils import simplejson


def oauth_required(reverse_url=None, reverse_args=[]):
    """
        Decorator function that redirects to passed if not authenticated with oauth
        Passing the reverse URL to redirect if oauth is authenticated
    """
    def wrap(f):
        def wrapped_f(request,*args, **kwargs):

            if 'credentials' not in request.session:
                if request.is_ajax():
                    content = simplejson.dumps({"authenticated":"0"})
                    return http.HttpResponse(content, content_type='application/json')
                else:
                    return HttpResponseRedirect(reverse(reverse_url,args=reverse_args))
            return f(request, *args, **kwargs)
        return wrapped_f
    return wrap